<?php
namespace Components\Parameter\First;

class Service {
	private $models = [];
	public function getModelsByKey($key = null) {
		if(is_null($key)) {
			return $this -> models;
		}

		if(empty($key)) {
			return false;
		}

		if(isset($this -> models[$key]) && !empty($this -> models[$key]) && is_object($this -> models[$key])) {
			return $this -> models[$key];
		}

		$model = $this -> findFirstByKey($key);
		if($model['code'] != 0) {
			return false;
		}

		return $this -> models[$key] = $model['model'];
	}

	public function find($parameters = []) {
		$model = Model::find($parameters);
		if(!$model -> valid()) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return ['code' => 0, 'models'=>$model];
	}

	public function findFirst($parameters = []) {
		$model = Model::findFirst($parameters);
		if(!$model) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return ['code' => 0, 'model'=>$model];
	}

	public function findFirstByKey($key) {
		if(empty($key)) {
			return ['code' => -1, 'message' => '数据不存在或已删除'];
		}

		return $this -> findFirst(['key = "' . $key . '"']);
	}

	public function update($key, $data) {
		if(!$this -> getModelsByKey($key)) {
			return ['code' => -1, 'message'=>'数据不存在或已删除'];
		}

		$data['last_update_time'] = isset($data['last_update_time'])?$data['last_update_time']:time();

		if(!$this -> models[$key] -> update($data)) {
			$messages = $this -> models[$key] -> getMessages();
			return ['code' => -1, 'message' => $messages[0] -> getMessage()];
		}

		return ['code' => 0, 'model'=>$this -> models[$key]];
	}
}
